﻿using SuperiorCommon;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Http;

namespace Aly.Sms
{
    public class SmsManager
    {
        private SmsManager(){}
        private static SmsManager _instance = null;
        private static readonly object locker = new object();
        public static SmsManager Instance
        {
            get
            {
                if(_instance==null)//为了性能，
                {
                    lock (locker)
                    {
                        if (_instance == null)//防止多线程下，lock完后，被其他线程给实例化了
                        {
                            _instance = new SmsManager();
                        }
                    }
                }
                return _instance;
            }
        }

        public int Send(string phone,string code)
        {
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", ConfigSettings.Instance.SmsAccessKey, ConfigSettings.Instance.SmsAccessSecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.Method = MethodType.POST;
            request.Domain = "dysmsapi.aliyuncs.com";
            request.Version = "2017-05-25";
            request.Action = "SendSms";
            // request.Protocol = ProtocolType.HTTP;
            request.AddQueryParameters("PhoneNumbers", phone);
            request.AddQueryParameters("SignName", ConfigSettings.Instance.SmsSignName);
            request.AddQueryParameters("TemplateCode", ConfigSettings.Instance.SmsTemplateCode);
            request.AddQueryParameters("TemplateParam", "{\"code\":\""+code+"\"}");
            try
            {
                CommonResponse response = client.GetCommonResponse(request);
                return response.Data.Contains("OK")?200:-1;
                //Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
            }
            catch (ServerException e)
            {
                LogManger.Instance.WriteLog(e.ErrorMessage);
                return -1;
            }
           
        }
    }
}
